import React, { Component } from "react";
import { Form, Icon, Input, Button, Alert, message } from "antd";
import { findModuleConfigApi } from '../js/bigScreen.js'
import { loginApi, getPublickeyApi } from "../js/api.js";
import JSEncrypt from 'jsencrypt'
import rgb from 'rgb'
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';


const FormItem = Form.Item;



class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            msg: "",
            //新增图片验证码
            code: '',
            codeLength: 4,
            fontSizeMin: 20,
            fontSizeMax: 22,
            backgroundColorMin: 240,
            backgroundColorMax: 250,
            colorMin: 10,
            colorMax: 20,
            lineColorMin: 40,
            lineColorMax: 180,
            contentWidth: 96,
            contentHeight: 38,
            showError: false, // 默认不显示验证码的错误信息
            showCode: false,
            showFlag: 0
        };

        // if (window.location.protocol == 'http:') {
        //     window.location.href="https://tidukeji.cn"
        // }
      
    }

    //密码强弱判断
    judgePassword(password){ 
        var reg = /^[0-9]{6,16}$|^[a-zA-Z]{6,16}$/   //全是数字或全是字母     6-16个字符   弱
        var reg2 = /^[A-Za-z0-9]{6,16}$/ //数字、26个英文字母      6-16个字符   中
        var reg3 = /^(?![\d]+$)(?![a-zA-Z]+$)(?![~`!@#%^&*()\\_+\-={}|'";:,./<>?]+$)[\da-zA-Z~`!@#%^&*()\\_+\-={}|'";:,./<>?]{6,16}$/ // 由数字、26个英文字母或者下划线组成的字符串    6-16个字符  强
        
        if(password.length<6)
        {
            return 1
        }
        else if(password.length>16)
        {
            return 2
        }
        else if(password.match(reg)){
            console.log("----------弱")
            return 3
        }else if(password.match(reg2)){
            console.log("----------中")
            return 0
        }else if(password.match(reg3)){
            console.log("----------高")
            return 0
        }else{
            return 4
        }
    }

    handlefind(departmentId) {


        findModuleConfigApi(departmentId).then((res) => {
            if (res.data.result.length != 0) {

                let checked = res.data.result[0].moduleWatch
                let value=res.data.result[0].moduleWatch||"巡更,巡检"
             sessionStorage.setItem("arr", value)

            }
            else {
                sessionStorage.setItem("arr", "巡更,巡检")

            }


        }).catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message);
            }
            console.info(e.config)
        });
    }
    handleSubmit(e) {
        e.preventDefault();
        let showFlag1
        showFlag1 = this.state.showFlag + 1
        this.setState({
            showFlag: showFlag1
        })
    //    console.log("showFlag==================", this.state.showFlag)
        if(this.state.showFlag >= 2){
            this.setState({
                showCode: true
            })
            this.drawPic();
            if(this.state.showFlag >= 3){
                if(this.state.sendcode.toLowerCase() != this.state.code.toLowerCase()) {
                    this.setState({
                        visible : true,
                        msg : "验证码错误"
                    })
                  }
            }
            
            
        }
        // 新增
        // this.setState({
        //     showCode: true
        // })
        // this.drawPic();
        // if(this.state.sendcode.toLowerCase() != this.state.code.toLowerCase()) {
        //     this.setState({
        //         visible : true,
        //         msg : "验证码错误"
        //     })
        //   }

        
        this.props.form.validateFields((err, values) => {
            console.log(e)
            if (!err) {
                let that = this;
                //前端向后台发送请求之前，先请求后台获取公钥
                let publicKey = null;
                getPublickeyApi()
                    .then((res) => {
                        var encrypt = new JSEncrypt();
                        //后台生成的公钥
                        publicKey = res.data.publicKey
                        encrypt.setPublicKey(publicKey);
                        //    let userName = encrypt.encrypt(values.userName.trim());
                        let password = encrypt.encrypt(values.password.trim());
                      
                        //登录
                        loginApi(values.userName, values.password)
                        // loginApi(values.userName, password)
                            .then((res) => {
                                if (res.data.result == "success") {
                                    this.handlefind(res.data.departmentId)
                                    //sessionStorage的用法： 存储客户端临时信息的对象
                                    sessionStorage.setItem("username", values.userName);
                                    //新增
                                    sessionStorage.setItem("password", values.password);
                                    sessionStorage.setItem("userId", res.data.id);
                                    sessionStorage.setItem("identityId", res.data.identityId);
                                    localStorage.setItem("departmentId", res.data.departmentId);
                                    localStorage.setItem("departmentName", res.data.departmentName);
                                    sessionStorage.setItem("departmentId", res.data.departmentId);
                                    sessionStorage.setItem("departmentName", res.data.departmentName == "绍兴市直属" ? "绍兴市教育局" : res.data.departmentName);
                                    sessionStorage.setItem("departmentType", res.data.departmentType);
                                    sessionStorage.setItem("route", res.data.route);
                                    sessionStorage.setItem("schoolLevel", res.data.schoolLevel);
                                    sessionStorage.setItem("parent", res.data.parent);


                                    var flag = this.judgePassword(values.password)
                                    sessionStorage.setItem("judgePassword", flag)
                                    if(flag > 0){
                                        that.props.history.push("/updatePwd");
                                        message.info("密码修改界面！")
                                    }else{
                                        that.props.history.push(res.data.route);
                                        message.loading('登录成功', [1])
                                    }
                                    
                                } else if (res.data.result == "userError") {
                                    that.setState({
                                        visible: true,
                                        msg: "用户名密码错误"
                                    });
                                } else if (res.data.result == "nopermission") {
                                    that.setState({
                                        visible: true,
                                        msg: "该用户无权限"
                                    });
                                } else if (res.data.result == "nullCode") {
                                    that.setState({
                                        visible: true,
                                        msg: "账号密码不能为空"
                                    });
                                } else {
                                    that.setState({
                                        visible: true,
                                        msg: "发生未知错误"
                                    });
                                }
                            })
                            .catch((e) => {
                                if (e.response) {
                                    //请求已发出，服务器返回状态码不是2xx。
                                    console.info(e.response.data)
                                    console.info(e.response.status)
                                    console.info(e.response.headers)
                                } else if (e.request) {
                                    // 请求已发出，但没有收到响应
                                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                                    // 在node中是一个http.ClientRequest实例
                                    console.info(e.request)
                                } else {
                                    //发送请求时异常，捕捉到错误
                                    console.info('error', e.message)
                                }
                                console.info(e.config)

                            });

                    })
                    .catch((e) => {
                        console.log(e)
                    });

            }else{
                console.log(e)
            }
        });
    }

    handleClose() {
        this.setState({ visible: false });
    }

    componentWillMount() {
        this.canvas = React.createRef()
    }
    //新增
    componentDidMount() {
        // this.setState({
        //     showCode: true
        // })
        // this.drawPic();
    }
    //新增
    // 生成一个随机数
    randomNum = (min, max) => {
        return Math.floor(Math.random() * (max - min) + min)
    }
    //新增
    drawPic = () => {
        this.randomCode()
    }
    //新增
    // 生成一个随机的颜色
    randomColor(min, max) {
        const r = this.randomNum(min, max)
        const g = this.randomNum(min, max)
        const b = this.randomNum(min, max)
        return `rgb(${r}, ${g}, ${b})`
    }

    drawText(ctx, txt, i) {
        ctx.fillStyle = this.randomColor(this.state.colorMin, this.state.colorMax)
        const fontSize = this.randomNum(this.state.fontSizeMin, this.state.fontSizeMax)
        ctx.font = fontSize + 'px SimHei'
        const padding = 10;
        const offset = (this.state.contentWidth - 40) / (this.state.code.length - 1)
        let x = padding;
        if (i > 0) {
            x = padding + (i * offset)
        }
        let y = this.randomNum(this.state.fontSizeMax, this.state.contentHeight - 5)
        if (fontSize > 40) {
            y = 40
        }
        const deg = this.randomNum(-10, 10)
        // 修改坐标原点和旋转角度
        ctx.translate(x, y)
        ctx.rotate(deg * Math.PI / 180)
        ctx.fillText(txt, 0, 0)
        // 恢复坐标原点和旋转角度
        ctx.rotate(-deg * Math.PI / 180)
        ctx.translate(-x, -y)
    }

    drawLine(ctx) {
        // 绘制干扰线
        for (let i = 0; i < 1; i++) {
            ctx.strokeStyle = this.randomColor(this.state.lineColorMin, this.state.lineColorMax)
            ctx.beginPath()
            ctx.moveTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
            ctx.lineTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
            ctx.stroke()
        }
    }

    drawDot(ctx) {
        // 绘制干扰点
        for (let i = 0; i < 100; i++) {
            ctx.fillStyle = this.randomColor(0, 255)
            ctx.beginPath()
            ctx.arc(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight), 1, 0, 2 * Math.PI)
            ctx.fill()
        }
    }

    reloadPic = () => {
        this.drawPic()
        this.props.form.setFieldsValue({
            sendcode: '',
        });
    }
    changeCode = e => {
        if (e.target.value.toLowerCase() !== '' && e.target.value.toLowerCase() !== this.state.code.toLowerCase()) {
            this.setState({
                showError: true
            })
        } else if (e.target.value.toLowerCase() === '') {
            this.setState({
                showError: false
            })
        } else if (e.target.value.toLowerCase() === this.state.code.toLowerCase()) {
            this.setState({
                showError: false
            })
        }
    }
    randomCode() {
        let random = ''
        // 去掉了I l i o O
        const str = 'QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm1234567890'
        for (let i = 0; i < this.state.codeLength; i++) {
            let index = Math.floor(Math.random() * 57);
            random += str[index];
        }
        this.setState({
            code: random
        }, () => {
            let canvasSreen = this.canvas.current;
            let ctx = canvasSreen.getContext('2d')
            ctx.textBaseline = 'bottom'
            // 绘制背景
            ctx.fillStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax)
            ctx.fillRect(0, 0, this.state.contentWidth, this.state.contentHeight)
            // 绘制文字
            for (let i = 0; i < this.state.code.length; i++) {
                this.drawText(ctx, this.state.code[i], i)
            }
            // this.drawLine(ctx)
            // this.drawDot(ctx)
        })
        
    }


    // redirect = () => {
    //     // this.setState({
    //     //     buttonLoading: true
    //     // })
    //    let name = sessionStorage.getItem("departmentName")
       
    //     let key = "123456******789"
    //     getScreenSecretApi(name, key).then((res) => {
    //         // this.setState({
    //         //     buttonLoading: false
    //         // })
    //         // const w = window.open('https://tidukeji.cn/edubigscreen/' + res.data);
    //         // window.location = 'https://tidukeji.cn/edubigscreen/' + res.data;
    //         let strLen = JSON.stringify(res.data).length;

    //         const w = window.open('https://tidukeji.cn/edubigscreen/' + JSON.stringify(res.data).substring(1, strLen-1).split("=")[0]);
    //     })
    // }
  

    render() {

        
        const { getFieldDecorator } = this.props.form;
        const { current } = this.state;
        const suffix =
            <div style={{
                height: "32px",
                width: "88px",
                justifyContent: "right", }}>
                <canvas
                    onClick={this.reloadPic}
                    ref={this.canvas}
                    width='90'
                    height='32'>
                </canvas>
            </div>
        return (
            <div className="login-background">
                <div className="login">
                    <div style={{
                        height: "400px",
                        width: "520px",
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                        marginTop : "20px"
                    }}>
                        <Form onSubmit={this.handleSubmit.bind(this)} className="login-form">
                            <div style={{
                                textAlign: "center",
                                marginBottom: "30px"
                            }}>
                                <img
                                    style={{
                                        display: "inline-block",
                                        width: "50px",
                                        marginRight: "20px"
                                    }}
                                    src={require('../img/newLogo.png')} />
                                <img
                                    style={{
                                        height: "40px"
                                    }}
                                    src={require('../img/newLoginTitle.png')} />
                            </div>
                            <FormItem>
                                {getFieldDecorator("userName", {
                                    rules: [{ required: true, message: "请输入用户名!" }]
                                })(
                                    <Input
                                        size="large"
                                        prefix={
                                            <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                                        }
                                        placeholder="帐号"
                                    />
                                )}
                            </FormItem>
                            <FormItem>
                                {getFieldDecorator("password", {
                                    rules: [{ required: true, message: "请输入密码!" }]
                                })(
                                    <Input.Password
                                        size="large"
                                        prefix={
                                            <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                        }
                                        type="password"
                                        placeholder="密码"
                                        // iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                    />
                                )}
                            </FormItem>
                          {

                          this.state.showCode ?
                            (<Form.Item>
                                {getFieldDecorator('sendcode', {
                                    rules: [
                                        { required: true, message: '请输入校验码!' },
                                        {
                                            validator: (rule, value, callback) => {
                                                if (value) {
                                                    if (value.toLowerCase() === this.state.code.toLowerCase()) {
                                                        callback()
                                                        this.setState({
                                                            sendcode: value,
                                                            showError: false
                                                        })
                                                    } 
                                                    else {
                                                      //  callback('请输入正确的验证码')
                                                        this.setState({
                                                            sendcode: value,
                                                            showError: true,
                                                        })
                                                    }
                                                } else {
                                                    callback()
                                                }
                                            }
                                        }
                                    ],
                                })(
                                    
                                    <Input
                                        size="large"
                                        prefix={<Icon type="exclamation-circle" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                        suffix={suffix}
                                        onChange={this.changeCode}
                                        maxLength={4}
                                        placeholder="请输入校验码"
                                    />,
                                )}
                            </Form.Item>) : null
                            
                            }
                        
                            {
                                this.state.visible ?
                                    (
                                        <FormItem>
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        </FormItem>
                                    ) : null
                            }
                            <FormItem>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    className="login-form-button">
                                    登录
                                </Button>
                            </FormItem>
                        </Form>
                    </div>
                   
                </div>

                <div style={{ width: "100%", textAlign: "left", position: "fixed", zIndex: 3, bottom: 0, left: "5%" }}>

                    <p style={{ textAlign: "left", height: 20, color: "#ffffff" }}>
                        CopyRight{"   "}  梯度安全网格版权所有 {"  "}
                        <a href="http://beian.miit.gov.cn/" target="_blank" style={{
                            display: "inline-block",
                            textDecoration: "none",
                            color: "#ffffff"
                        }}> 浙ICP备19000794-1号</a>
                    </p>


                    <p style={{ textAlign: "left", height: 20, color: "#ffffff" }}>
                        <img src="../img/beiantubiao.png" style={{ display: "inline" }} />
                        < a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010802010966"
                            style={{ display: 'inline', textDecoration: 'none', }}>浙公网安备 33010802010966号</a></p>


                </div>
            </div>
        );
    }
}

const Login = Form.create()(LoginForm);

export default Login;
